/**
 * 
 */

package com.the9tcat.everydayapp;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.widget.RemoteViews;

import com.the9tcat.everydayapp.data.AppInfo;
import com.the9tcat.everydayapp.db.AppInfoTable;
import com.the9tcat.everydayapp.widget.AppWidgetLarge;
import com.the9tcat.hadi.DefaultDAO;

/**
 * @author jianhpin
 */
public class AppService extends Service {

    int i = 0;
    List<AppInfo> mInfo;

    /*
     * (non-Javadoc)
     * @see android.app.Service#onBind(android.content.Intent)
     */
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        DefaultDAO dao = new DefaultDAO(this);
        @SuppressWarnings("unchecked")
		List<AppInfoTable> list = (List<AppInfoTable>) dao.select(AppInfoTable.class, false, null, null, null, null, null, null);
        mInfo = new ArrayList<AppInfo>(list.size());
        for (AppInfoTable table: list) {
        	AppInfo info = new AppInfo();
        	info.id = table.id;
        	info.name = table.name;
        	info.description = table.description;
        	try {
				FileInputStream fis = new FileInputStream(getFilesDir().getAbsolutePath() + "/icon/icon_" + info.id + ".png");
				info.icon = BitmapFactory.decodeStream(fis);
				fis.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			info.recommend = table.recommend;
			if (info.id == null || info.name == null || info.description == null || info.icon == null || info.recommend == 0) {
				stopSelf();
			}
			mInfo.add(info);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    	if (mInfo == null || mInfo.size() == 0) {
    		return 0;
    	}
        AlarmManager alarmManager = (AlarmManager) this
                .getSystemService(Context.ALARM_SERVICE);
        Intent in = new Intent(this, AppService.class);
        PendingIntent pendingIntent = PendingIntent
                .getService(this, 0, in, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManager.cancel(pendingIntent);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System
                .currentTimeMillis() + 10 * 1000, pendingIntent);
        
        i = (++i) % mInfo.size();
        updateLargeWidget(mInfo.get(i));
        return super.onStartCommand(intent, flags, startId);
    }

    private void updateLargeWidget(AppInfo app) {
        AppWidgetManager awm = AppWidgetManager.getInstance(this);
        RemoteViews views = new RemoteViews(getPackageName(),
                                            R.layout.widget_large_layout);
        views.setTextViewText(R.id.info, app.description);
        views.setTextViewText(R.id.name, app.name);
        views.setImageViewBitmap(R.id.icon, app.icon);
        views.setTextViewText(R.id.down_count, app.down_time);
        setLevel(views, app.recommend);

        // 设置事件
        Intent in1 = new Intent(this, AppDetailActivity.class);
        PendingIntent pi1 = PendingIntent
                .getActivity(this, 0, in1, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.go, pi1);
        Intent in2 = new Intent(this, AppService.class);
        PendingIntent pi2 = PendingIntent
                .getService(this, 0, in2, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.next, pi2);

        awm.updateAppWidget(new ComponentName(this, AppWidgetLarge.class),
                            views);
    }

    private void setLevel(RemoteViews view, int level) {
        int on = R.drawable.star_on;
        int off = R.drawable.star_off;
        int half = R.drawable.star_half;
        switch (level) {
            case 1:
                setResourceById(view, half, off, off, off, off);
                break;
            case 2:
                setResourceById(view, on, off, off, off, off);
                break;
            case 3:
                setResourceById(view, on, half, off, off, off);
                break;
            case 4:
                setResourceById(view, on, on, off, off, off);
                break;
            case 5:
                setResourceById(view, on, on, half, off, off);
                break;
            case 6:
                setResourceById(view, on, on, on, off, off);
                break;
            case 7:
                setResourceById(view, on, on, on, half, off);
                break;
            case 8:
                setResourceById(view, on, on, on, on, off);
                break;
            case 9:
                setResourceById(view, on, on, on, on, half);
                break;
            case 10:
                setResourceById(view, on, on, on, on, on);
                break;
        }
    }

    private void setResourceById(RemoteViews view, int s1, int s2, int s3,
            int s4, int s5) {
        view.setImageViewResource(R.id.level_1, s1);
        view.setImageViewResource(R.id.level_2, s2);
        view.setImageViewResource(R.id.level_3, s3);
        view.setImageViewResource(R.id.level_4, s4);
        view.setImageViewResource(R.id.level_5, s5);
    }
}
